package shangguigu_juc.sync;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

// 资源类
@Data
@NoArgsConstructor
@AllArgsConstructor
class Ticket {
    private int ticketNum;
    private int saleNum;
    public void sale() {
        if (ticketNum > 0) {
            System.out.println(Thread.currentThread().getName() + ": 卖出第" + (++saleNum) + "张" + " 剩余：" + --ticketNum + "张");
        }
    }
}

// 操作资源的任务类
class Task implements Runnable {

    private Ticket ticket;

    public Task(Ticket ticket) {
        this.ticket = ticket;
    }

    private final Object object = new Object();

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (object) {
                ticket.sale();
            }
        }
    }
}

// 客户端程序
public class MySaleTicket {

    public static void main(String[] args) {

        Task task = new Task(new Ticket(30,0));
        Thread t1 = new Thread(task, "T1");
        Thread t2 = new Thread(task, "T2");
        Thread t3 = new Thread(task, "T3");
        t1.start();
        t2.start();
        t3.start();
    }
}
